package org.xiaov.lunasql.spring.mybatis;

import org.apache.ibatis.session.SqlSessionFactory;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.SmartLifecycle;

/**
 * <p>
 * SqlSessionFactorySmartLifecycle
 * </p>
 *
 * @author lzq
 * @since 2024/12/27 08:45
 */
public class SqlSessionFactorySmartLifecycle implements ApplicationContextAware, SmartLifecycle {

    private volatile boolean running = false;

    private ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }

    @Override
    public void start() {
        if (!running) {
            SqlSessionFactory sqlSessionFactory = applicationContext.getBean(SqlSessionFactory.class);
            sqlSessionFactory.getConfiguration().addInterceptor(new MybatisTransformInterceptor());
            running = true;
        }
    }

    @Override
    public void stop() {
        running = false;
    }

    @Override
    public boolean isRunning() {
        return running;
    }
}
